package com.pulse.base.controller;

import com.pulse.base.domain.CircuitMeasure;
import com.pulse.base.domain.JobDispatch;
import com.pulse.base.domain.vo.ParamVo;
import com.pulse.base.service.IJobDispatchService;
import com.pulse.common.annotation.Log;
import com.pulse.common.core.controller.BaseController;
import com.pulse.common.core.domain.AjaxResult;
import com.pulse.common.core.page.TableDataInfo;
import com.pulse.common.enums.BusinessType;
import com.pulse.common.exception.ServiceException;
import com.pulse.quartz.util.CronUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/base/jobDispatch")
public class JobDispatchController extends BaseController {

    @Autowired
    private IJobDispatchService jobDispatchService;

    @PreAuthorize("@ss.hasPermi('base:jobDispatch:list')")
    @GetMapping("/list")
    public TableDataInfo list(JobDispatch jobDispatch){
        startPage();
        List<JobDispatch> list = jobDispatchService.selectJobDispathList(jobDispatch);
        return getDataTable(list);
    }

    @PostMapping("/startTest")
    public AjaxResult startTest(@RequestBody CircuitMeasure circuitMeasure){
        try{
            return AjaxResult.success(jobDispatchService.startTest(circuitMeasure));
        }
        catch (ServiceException e){
            return AjaxResult.error(e.getMessage());
        }
    }

    @PreAuthorize("@ss.hasPermi('base:jobDispatch:edit')")
    @Log(title = "周期测试", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody JobDispatch jobDispatch){
        try{
            return toAjax(jobDispatchService.updateJobDispatch(jobDispatch));

        }catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
    }

    @GetMapping("/listByDevice/{deviceNo}")
    public AjaxResult list(@PathVariable("deviceNo") String deviceNo){
        List<JobDispatch> list = jobDispatchService.selectByDeviceNo(deviceNo);
        return success(list);
    }

    @PutMapping("/setCron")
    public AjaxResult setCron(@RequestBody ParamVo paramVo){
        if (!CronUtils.isValid(paramVo.getCronExpression()))
        {
            return error("修改任务失败，Cron表达式不正确");
        }
        return toAjax(jobDispatchService.setCron(paramVo));
    }
}
